// @ts-ignore
import nprogress from "nprogress";
// 引入nprogress的样式
import "nprogress/nprogress.css";
import useUserStore from "@/store/modules/user";
import pinia from "./store/index";
import setting from "@/setting";
import router from "./router";
let userStore = useUserStore(pinia);
// 路由守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  // 更改网页名称
  if (to.meta.title) {
    document.title = `${setting.title} -${to.meta.title}`;
  }
  nprogress.start();
  // 路由鉴权
  if (userStore.token) {
    // 已登录,不能去login页面
    if (to.path == "/login") {
      next({ path: "/" });
    } else {
      // 是否有用户信息
      if (userStore.username) {
        // 有用户信息,直接放行
        next();
      } else {
        // 没有用户信息,先发请求捞用户信息，再放行
        try {
          await userStore.getUserInfo();
          next({ ...to });
        } catch (e) {
          // token过期或用户手动修改本地存储的token
          await userStore.userLogout();
          next({ path: "/login", query: { redirect: to.path } });
        }
      }
    }
  } else {
    //未登录，只能去login页面
    if (to.path == "/login") {
      next();
    } else {
      next({ path: "login", query: { redirect: to.path } });
    }
  }
});
router.afterEach((to: any, from: any) => {
  nprogress.done();
});
